package com.yunshipei.ui.fragment;


import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.TextureView;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.JavascriptInterface;
import android.widget.RelativeLayout;

import com.yunshipei.common.Globals;
import com.yunshipei.common.UserLoginDataParser;
import com.yunshipei.common.manager.EnterConfig;
import com.yunshipei.core.common.DataJSCallback;
import com.yunshipei.core.manager.TabManager;
import com.yunshipei.core.net.EnterClient;
import com.yunshipei.core.utils.ViewUtils;
import com.yunshipei.core.utils.YspFunUtils;
import com.yunshipei.enterplorer.BuildConfig;
import com.yunshipei.enterplorer.R;
import com.yunshipei.manager.YspPreferences;
import com.yunshipei.model.HomeAppsBean;
import com.yunshipei.model.MainExtraBean;
import com.yunshipei.model.UserInfo;
import com.yunshipei.model.YspEvent;
import com.yunshipei.utils.ToastUtils;

import org.chromiun.net.ProxyChangeListener;
import org.json.JSONException;
import org.json.JSONObject;
import org.xwalk.core.XWalkResourceClient;
import org.xwalk.core.XWalkUIClient;
import org.xwalk.core.XWalkView;
import org.xwalk.core.XWalkWebResourceRequest;
import org.xwalk.core.XWalkWebResourceResponse;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.rong.eventbus.EventBus;
import okhttp3.Cookie;

public class H5HomeFragment extends BaseNavItemFragment {

    private static final String BUNDLE_H5_HOME_DATA = "bundle.h5.home.data";

    private HomeFragment.OnFragmentInteractionListener onFragmentInteractionListener;

    public static H5HomeFragment newInstance(MainExtraBean mainExtraBean) {
        H5HomeFragment h5HomeFragment = new H5HomeFragment();
        Bundle bundle = new Bundle();
        bundle.putSerializable(BUNDLE_H5_HOME_DATA, mainExtraBean);
        h5HomeFragment.setArguments(bundle);
        return h5HomeFragment;
    }

    @Bind(R.id.h5_web_view)
    protected XWalkView mWebView;
    @Bind(R.id.h5_loading_view)
    protected RelativeLayout mLoadingView;

    private String mUrl = "";
    private MainExtraBean mMainExtraBean;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof HomeFragment.OnFragmentInteractionListener) {
            onFragmentInteractionListener = (HomeFragment.OnFragmentInteractionListener) context;
        }
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        mMainExtraBean = (MainExtraBean) getArguments().getSerializable(BUNDLE_H5_HOME_DATA);
        if (mMainExtraBean != null) {
            String onLineUrl = mMainExtraBean.getOnLineHome();
            if (!TextUtils.isEmpty(onLineUrl)) {
                mUrl = onLineUrl;
            } else {
                mUrl = "file://" + getActivity().getFilesDir().getPath() + File.separator + Globals.APP_WEB_ROOT_PATH + File.separator + mMainExtraBean.getHomeResDir() + File.separator + "index.html";
            }
        }
        configYspProxy();
    }

    //设置crosswalk的代理
    public void configYspProxy() {
        ProxyChangeListener.setProxyConfig(mProxyIP, mProxyPort, null, mExclusionList);
    }

    //从BrowserFragment切换到HomeFragment需要重新设置crosswalk的代理
    public void onEventMainThread(YspEvent.ConfigProxy configProxy) {
        configYspProxy();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_h5_xwalk_view, container, false);
        ButterKnife.bind(this, view);
        return view;
    }

    @SuppressLint("SetJavaScriptEnabled")
    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.addJavascriptInterface(redcore, "redcore");
        mWebView.setResourceClient(new XWalkResourceClient(mWebView) {
            @Override
            public boolean shouldOverrideUrlLoading(XWalkView view, String url) {

                Uri uri = Uri.parse(url);
                String path = "";
                if (uri != null) {
                    path = uri.getEncodedPath();
                }
                if (url.equals(mUrl) || (!TextUtils.isEmpty(path) && path.endsWith("search.html"))) {
                    view.loadUrl(url);
                    return false;
                } else {
                    onFragmentInteractionListener.openWebApp(url);
                    return true;
                }
            }

            @Override
            public XWalkWebResourceResponse shouldInterceptLoadRequest(XWalkView view, XWalkWebResourceRequest request) {
                String url = request.getUrl().toString();
                if (url.endsWith("_init.js")) {
                    try {
                        InputStream is = view.getContext().getAssets().open("empty");
                        return super.createXWalkWebResourceResponse("text/javascript", "UTF-8", is);
                    } catch (Exception ignored) {
                    }
                }
                return super.shouldInterceptLoadRequest(view, request);
            }

            @Override
            public void onLoadFinished(XWalkView view, String url) {
                super.onLoadFinished(view, url);
                EventBus.getDefault().post(new YspEvent.UpdateTabCount());
                if (mLoadingView.getVisibility() == View.VISIBLE) {
                    mLoadingView.setVisibility(View.INVISIBLE);
                }
            }
        });
        mWebView.setUIClient(new XWalkUIClient(mWebView));
        ProxyChangeListener.sendProxyReceiver(getActivity());
        mWebView.loadUrl(mUrl);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mWebView != null) {
            mWebView.onDestroy();
        }
        EventBus.getDefault().unregister(this);
    }

    //跟新首页标签数目
    public void onEventMainThread(YspEvent.UpdateTabCount event) {
        int size = TabManager.getInstance().getSize() + 1;
        if (mWebView != null) {
            mWebView.loadUrl("javascript: showMoreTabNumber(" + size + ");");
        }
    }

    private Object redcore = new Object() {
        @org.xwalk.core.JavascriptInterface
        @JavascriptInterface
        public String personalConfig() {
            JSONObject jsonObject = new JSONObject();
            try {
                jsonObject.put("platform", "android");
                jsonObject.put("appVersion", BuildConfig.VERSION_NAME);
                jsonObject.put("themeColor", EnterConfig.getInstance().optGlobalColor());
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return jsonObject.toString();
        }

        @org.xwalk.core.JavascriptInterface
        @JavascriptInterface
        public void dropDownRefresh() {
            UserInfo userInfo = mMainExtraBean.getUserInfo();
            YspFunUtils.updateXCloudData(getActivity(), userInfo.getUuid(), userInfo.getCompanyId(), new DataJSCallback() {
                @Override
                public void error(String errorMsg) {
                    ToastUtils.showToast(errorMsg);
                    mWebView.reload(0);
                }

                @SuppressLint("ApplySharedPref")
                @Override
                public void success(String result) {
                    List<HomeAppsBean> homeApps = new UserLoginDataParser(getActivity()).dataJS2HomeApps(result);
                    EventBus.getDefault().post(new YspEvent.UpdateHomeApps(homeApps));
                    YspPreferences.getInstance().getSharedPreferences().edit().putString(Globals.YSP_DATA_JS, result).commit();
                    mWebView.reload(0);
                }
            });
        }

        @org.xwalk.core.JavascriptInterface
        @JavascriptInterface
        public void showScanView() {
            AndroidSchedulers.mainThread().createWorker().schedule(new Runnable() {
                @Override
                public void run() {
                    onFragmentInteractionListener.openQRCode();
                }
            });
        }

        @org.xwalk.core.JavascriptInterface
        @JavascriptInterface
        public String getDataJs() {
            return YspPreferences.getInstance().getSharedPreferences().getString(Globals.YSP_DATA_JS, "");
        }

        @org.xwalk.core.JavascriptInterface
        @JavascriptInterface
        public void showMoreTab() {
            AndroidSchedulers.mainThread().createWorker().schedule(new Runnable() {
                @Override
                public void run() {
                    onFragmentInteractionListener.onDrawerOpen();
                }
            });
        }

        @org.xwalk.core.JavascriptInterface
        @JavascriptInterface
        public String getCookie() {
            List<Cookie> cookies = EnterClient.getInstances().getManagerCookies();
            String cookieStr = "";
            if (cookies != null) {
                for (Cookie cookie : cookies) {
                    cookieStr = cookie.name() + "=" + cookie.value() + ";domain=" + cookie.domain();
                }
            }
            return cookieStr;
        }
    };

    private String webviewFileName = "";

    public String getHomeWebViewCaptureURL(boolean webViewVisible) {
        if (webViewVisible) {
            TextureView textureView = ViewUtils.findXWalkTextureView(mWebView);
            if (textureView != null) {
                Bitmap bitmap = textureView.getBitmap();
                try {
                    webviewFileName = getActivity().getCacheDir() + File.separator + System.currentTimeMillis() + ".jpg";
                    FileOutputStream fos = new FileOutputStream(webviewFileName);
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 7, fos);
                    fos.close();
                    bitmap.recycle();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return webviewFileName;
    }
}
